package com.hyy.lotterysystem.common.intercepter;

import com.hyy.lotterysystem.common.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {


    /**
     * 预处理，业务请求之前调用
     *
     * @param request
     * @param response
     * @param handler
     * @return
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
            //首先，在request的请求头中拿到jwt令牌
        String token=request.getHeader("user_token");
        log.info("获取到token:"+token);
        log.info("请求url:"+request.getRequestURI());

        //令牌解析
        Claims claims = JWTUtil.parseJWT(token);
        if(claims==null){
            log.error("jwt令牌解析失败！");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        log.info("jwt令牌解析成功，放行");
        return true;
    }
}
